package com.wskj.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wskj.common.core.domain.entity.SysUser;
import com.wskj.common.core.mybatisplus.core.ServicePlusImpl;
import com.wskj.common.core.page.PagePlus;
import com.wskj.common.core.page.TableDataInfo;
import com.wskj.common.utils.common.AssertUtils;
import com.wskj.common.utils.common.DateUtils;
import com.wskj.common.utils.common.PageUtils;
import com.wskj.system.mapper.SysUserMapper;
import com.wskj.system.service.ISysFeedbackService;
import com.wskj.system.bo.SysFeedbackAddBo;
import com.wskj.system.bo.SysFeedbackEditBo;
import com.wskj.system.bo.SysFeedbackQueryBo;
import com.wskj.system.domain.SysFeedback;
import com.wskj.system.mapper.SysFeedbackMapper;
import com.wskj.system.vo.web.SysFeedbackVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 意见反馈Service业务层处理
 *
 * @author wsdz
 * @date 2022-08-22
 */
@Service
@AllArgsConstructor
public class SysFeedbackServiceImpl extends ServicePlusImpl<SysFeedbackMapper, SysFeedback> implements ISysFeedbackService {

    private final SysUserMapper sysUserMapper;

    @Override
    public SysFeedbackVo queryById(Long feedbackId){
        return getVoById(feedbackId, SysFeedbackVo.class);
    }

    @Override
    public TableDataInfo<SysFeedbackVo> queryPageList(SysFeedbackQueryBo bo) {
        Page<SysFeedbackVo> page = baseMapper.queryPageList(PageUtils.buildPage(),bo);
        if(page != null && CollectionUtils.isNotEmpty(page.getRecords())){
            List<String> userIdList = page.getRecords().stream().map(SysFeedbackVo::getCreateBy).collect(Collectors.toList());
            LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserLambdaQueryWrapper.in(SysUser::getUserId,userIdList);
            List<SysUser> sysUserList = sysUserMapper.selectList(sysUserLambdaQueryWrapper);
            Map<Long,SysUser> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
            page.getRecords().forEach(s1->{
                if(sysUserMap.containsKey(Long.parseLong(s1.getCreateBy()))){
                    SysUser sysUser = sysUserMap.get(Long.parseLong(s1.getCreateBy()));
                    s1.setCreateByName(sysUser.getNickName());
                }
            });
        }
        return PageUtils.buildDataInfo(page);
    }

    @Override
    public List<SysFeedbackVo> queryList(SysFeedbackQueryBo bo) {
        return listVo(buildQueryWrapper(bo), SysFeedbackVo.class);
    }

    private QueryWrapper<SysFeedback> buildQueryWrapper(SysFeedbackQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<SysFeedback> lqw = new QueryWrapper();
        lqw.lambda().eq(StrUtil.isNotBlank(bo.getFeedbackDesc()), SysFeedback::getFeedbackDesc, bo.getFeedbackDesc());
        lqw.lambda().eq(StrUtil.isNotBlank(bo.getFeedbackVoucher()), SysFeedback::getFeedbackVoucher, bo.getFeedbackVoucher());
        lqw.lambda().eq(bo.getFeedbackContact() != null, SysFeedback::getFeedbackContact, bo.getFeedbackContact());
        lqw.lambda().eq(StrUtil.isNotBlank(bo.getFeedbackReplyDesc()), SysFeedback::getFeedbackReplyDesc, bo.getFeedbackReplyDesc());
        lqw.lambda().eq(bo.getFeedbackReplyTime() != null, SysFeedback::getFeedbackReplyTime, bo.getFeedbackReplyTime());
        // 时间范围筛选
        String startEndRange = (String) params.get("startEndRange");
        if(StringUtils.isNotBlank(startEndRange)){
            String startDateStr = startEndRange.split(",")[0];
            String endDateStr = startEndRange.split(",")[1];
            lqw.lambda().ge(SysFeedback::getCreateTime,DateUtils.parseDate(startDateStr));
            lqw.lambda().le(SysFeedback::getCreateTime, DateUtils.parseDate(endDateStr));
        }
        if(bo.getParams() != null && bo.getParams().get("beginTime")!=null){
            lqw.lambda().apply("DATE_FORMAT(CREATE_TIME,'%Y-%m-%d') >= '" + bo.getParams().get("beginTime") + "'");
        }
        if(bo.getParams() != null && bo.getParams().get("endTime")!=null){
            lqw.lambda().apply("DATE_FORMAT(CREATE_TIME,'%Y-%m-%d') <= '" + bo.getParams().get("endTime") + "'");
        }
        // 创建者模糊查询
        lqw.lambda().like(StrUtil.isNotBlank(bo.getCreateBy()),SysFeedback::getCreateBy,bo.getCreateBy());
        lqw.lambda().orderByDesc(SysFeedback::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(SysFeedbackAddBo bo) {
        SysFeedback add = BeanUtil.toBean(bo, SysFeedback.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(SysFeedbackEditBo bo) {
        SysFeedback update = BeanUtil.toBean(bo, SysFeedback.class);
        // 反馈回复时间
        update.setFeedbackReplyTime(new Date());
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysFeedback entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public String importSysFeedback(List<SysFeedbackVo> sysFeedbackList) {
        AssertUtils.isTrue(CollectionUtils.isNotEmpty(sysFeedbackList), "导入数据不能为空");
        int successNum = 0;
        for (SysFeedbackVo sysFeedback : sysFeedbackList) {
            SysFeedback add = BeanUtil.toBean(sysFeedback, SysFeedback.class);
            save(add);
            successNum++;
        }
        String msg = String.format("导入完成，共计 %d 条数据，成功 %d 条！", sysFeedbackList.size(), successNum);
        if (successNum != sysFeedbackList.size()) {
            msg = msg + String.format("失败 %d 条！", sysFeedbackList.size() - successNum);
        }
        return msg;
    }
}
